﻿using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Web.Mvc;
using TweetsTranslate.Helpers;
using TweetsTranslate.Models;
using TweetsTranslate.Providers;

namespace TweetsTranslate.Controllers
{
    public class HomeController : Controller
    {
        private static MicrosoftTranslateProvider translatorProvider;
        private static TwitterProvider twitterProvider = null;
        private static List<TweetModel> listTweets;
        private static List<string> currentCaptchaAnswers;
        private static MD5 md5Hash;

        public HomeController()
        {
            md5Hash = MD5.Create();

            if (translatorProvider == null)
            {
                translatorProvider = new MicrosoftTranslateProvider();
                translatorProvider.Authenticate();
            }

            if (twitterProvider == null)
            {
                twitterProvider = new TwitterProvider();

            }

            if (listTweets == null)
            {
                listTweets = new List<TweetModel>();
            }
        }

        public ActionResult Index()
        {
            Session["captchaQuestion"] = HelperMethods.RequestCAPTCHA(ref currentCaptchaAnswers);
            Session["noResults"] = 5;
            Session["inputUserId"] = String.Empty;
            Session["languageListFrom"] = HelperMethods.CreateSelectedList(translatorProvider.GetLanguages());
            Session["languageListTo"] = HelperMethods.CreateSelectedList(translatorProvider.GetLanguages());

            return View(listTweets);
        }

        public ActionResult About()
        {
            return View("About");
        }

        [HttpPost]
        [MultipleButton(Name = "action", Argument = "SearchTweets")]
        public ViewResult SearchTweets(FormCollection formCollection)
        {
            listTweets.Clear();

            string captchaAnswer = formCollection["captchaAnswer"];
            string keywords = formCollection["inputKeywords"];
            string userId = formCollection["inputUserId"];
            int noResults = Int32.Parse(formCollection["inputNoTweets"]);

            Session["inputUserId"] = userId;
            Session["inputKeywords"] = keywords;
            Session["noResults"] = noResults;

            if (!ValidateUserInput(keywords, userId, captchaAnswer))
            {
                Session["captchaQuestion"] = HelperMethods.RequestCAPTCHA(ref currentCaptchaAnswers);

                HelperMethods.SetSelectedLanguage((IEnumerable<SelectListItem>)Session["languageListFrom"], formCollection["languageListTranslateFrom"]);
                HelperMethods.SetSelectedLanguage((IEnumerable<SelectListItem>)Session["languageListTo"], formCollection["languageListTranslateTo"]);
                return View("Index", listTweets);
            }

            string searchLanguage = formCollection["languageListTranslateFrom"];
            string translateLanguage = formCollection["languageListTranslateTo"];

            string errorMessage = string.Empty;
            listTweets = twitterProvider.SearchTweets(userId, keywords, searchLanguage, noResults, ref errorMessage);

            if (!errorMessage.Equals(string.Empty))
            {
                ModelState.AddModelError("inputUserId", errorMessage);
            }

            // ViewBag.languageList = sliList;
            Session["captchaQuestion"] = HelperMethods.RequestCAPTCHA(ref currentCaptchaAnswers);

            HelperMethods.SetSelectedLanguage((IEnumerable<SelectListItem>)Session["languageListFrom"], searchLanguage);
            HelperMethods.SetSelectedLanguage((IEnumerable<SelectListItem>)Session["languageListTo"], translateLanguage);

            return View("Index", listTweets);
        }

        [HttpPost]
        [MultipleButton(Name = "action", Argument = "TranslateTweets")]
        public ViewResult TranslateTweets(FormCollection formCollection)
        {
            string captchaAnswer = formCollection["captchaAnswer"];
            string keywords = formCollection["inputKeywords"];
            int noResults = Int32.Parse(formCollection["inputNoTweets"]);
            string searchLanguage = formCollection["languageListTranslateFrom"];
            string translateLanguage = formCollection["languageListTranslateTo"];

            foreach (TweetModel tweet in listTweets)
            {
                tweet.TranslatedText = translatorProvider.TranslateText(tweet.OriginalText, searchLanguage, translateLanguage);
            }

            HelperMethods.SetSelectedLanguage((IEnumerable<SelectListItem>)Session["languageListFrom"], searchLanguage);
            HelperMethods.SetSelectedLanguage((IEnumerable<SelectListItem>)Session["languageListTo"], translateLanguage);

            Session["inputKeywords"] = keywords;
            Session["captchaQuestion"] = HelperMethods.RequestCAPTCHA(ref currentCaptchaAnswers);
            Session["inputUserId"] = formCollection["inputUserId"];
            Session["noResults"] = noResults;

            return View("Index", listTweets);
        }

        private bool ValidateUserInput(string keywords, string userId, string captchaAnswer)
        {
            if ((keywords == null || keywords.Length == 0) && (userId == null || userId.Length == 0))
            {
                ModelState.AddModelError("inputTags", "The userId and keywords fields cannot be empty");
                return false;
            }

            bool answerFound = false;
            foreach (string answer in currentCaptchaAnswers)
            {
                if (HelperMethods.VerifyMd5Hash(md5Hash, captchaAnswer, answer))
                {
                    answerFound = true;
                    break;
                }
            }

            if (!answerFound)
            {
                ModelState.AddModelError("captchaAnswer", "The captcha answer is not valid!");
                return false;
            }

            return true;
        }
    }
}
